# -*- coding: utf-8 -*-
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from app_accounts.models import *
from app_TuringClass.models import *
from app_OnlineExam.models import *
from app_OnlineExam.forms import *
from django.core.exceptions import *
from django import forms
#send e-mail
from django.core.mail import send_mail
# 调用自行编写的lib库
from app_TuringClass.lib_appTuringClass import *
from app_TuringClass.turning_class import *

import time
import json

##考试模块
@csrf_exempt
def ShowQuestion(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
	courseid = request.POST['form']
	examid = request.POST['form2']
	ex = ExamPaperInfo.objects.get(ExamID = examid)
	examquestions = ex.ExamQuestions
	examnum = int(ex.ProblemNum)
	i = 0
	Questions = []
	for i in range(0,examnum):
		Question ={}
		q = examquestions.split('_',(examnum-1))[i]
		if q[0] =='s':
			question = SingleSelectProblem.objects.get(QuestionID = q[1:])
			Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
			Question['QuestionID'] = 's'+ '_'+ str(question.QuestionID)+'_'+examid
			Question['OptionA'] = question.OptionA
	 		Question['OptionB'] = question.OptionB
	 		Question['OptionC'] = question.OptionC
	 		Question['OptionD'] = question.OptionD
	 		Question['type1'] = 1
	 		Question['type2'] = 0
	 		Questions.append(Question)
		elif q[0] =='j':
			question = JudgementProblem.objects.get(QuestionID = q[1:])
			Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
			Question['QuestionID'] = 'j'+ '_'+ str(question.QuestionID)+'_'+examid
			Question['type1'] = 0
	 		Question['type2'] = 1
	 		Questions.append(Question)
	context ={
	 		'questions':Questions,
	 }
	return render(request, 'OnlineTestDemo.html', context)
@csrf_exempt
def AnswerQuestion(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
	i = 0
	score = 0
	item = request.POST.items()
	num = len(item)
	examid  = (str(item[0]).split(',',1)[0].split('\'',2)[1]).split('_',2)[2]
	Questions = []
	if request.POST:
		try:
			for i in range(0,num):
				Question ={}
				ID = str(item[i]).split(',',1)[0].split('\'',2)[1]
				answer = str(item[i]).split(',',1)[1].split('\'',2)[1]
				qtype = ID.split('_',2)[0]
				qid = int(ID.split('_',2)[1])
				if qtype == 's':
					question = SingleSelectProblem.objects.get(QuestionID = qid)
					Question['QuestionID'] =ID
					Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
					Question['OptionA'] = question.OptionA
	 				Question['OptionB'] = question.OptionB
	 				Question['OptionC'] = question.OptionC
	 				Question['OptionD'] = question.OptionD
	 				Question['type1'] = 1
	 				Question['type2'] = 0
	 				Question['my'] = answer
	 				Question['Analysis'] = question.Analysis
					if answer == question.SingleAnswer:
						score = score + int(question.Weight)
						Question['True'] = answer
					elif question.SingleAnswer =='A':
						Question['True'] = question.OptionA
					elif question.SingleAnswer =='B':
						Question['True'] = question.OptionB
					elif question.SingleAnswer =='C':
						Question['True'] = question.OptionC
					elif question.SingleAnswer =='D':
						Question['True'] = question.OptionD
					Questions.append(Question)
				elif qtype == 'j':
					question = JudgementProblem.objects.get(QuestionID = qid)
					Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
					Question['QuestionID'] = ID
					Question['type1'] = 0
	 				Question['type2'] = 1
					Question['Analysis'] = question.Analysis
					if answer == question.JudgementAnswer:
						if answer == 'A':
							Question['True'] = '选正确'
							Question['my'] = '正确'
						elif answer == 'B': 
							Question['True'] = '选错误'
							Question['my'] = '错误'
						score = score + int(question.Weight)
					elif answer !=question.JudgementAnswer:
						if answer == 'A':
							Question['True'] = '选错误'
							Question['my'] = '正确'
						elif answer == 'B':
							Question['True'] = '选正确'
							Question['my'] = '错误'
					Questions.append(Question)
			context ={
	 		'questions':Questions,
	 		'score':score,
	 		}
	 		if ScoreInfo.objects.filter(StuID = request.session['UserID'] ,ExamID =examid).exists():
	 			sc = ScoreInfo.objects.get(StuID = request.session['UserID'] ,ExamID =examid)
	 			sc.Score = str(score)
	 			sc.save()
	 		else:
	 			ScoreInfo(StuID = request.session['UserID'] ,ExamID =examid,Score = str(score)).save()
	 		return render(request,'ExamResult.html',context)
		except Exception, e:
			print Exam
			raise Http404
	return HttpResponse('Whoops!')

@csrf_exempt
def Exam(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
	courses = Course.objects.all()
	subjects = []
	exams =[]
	for course in courses :
		subject = {}
		subject['courseid'] = course.CourseID
		subject['coursename'] = course.CourseName
		subjects.append(subject)
	if request.POST :
		Exams = ExamPaperInfo.objects.filter(CourseID = request.POST['cid'])
		for Exam in Exams:
			exam = {}
			exam['examname'] = Exam.ExamName
			exam['examid'] =Exam.ExamID
			exams.append(exam)

		context ={
			'subjects':subjects,
			'exams':exams,
		}
		try:
			return HttpResponse(json.dumps(context))
		except Exception as e:
			print e


	context ={
			'subjects':subjects,
		}
	return render (request,'exam.html',context)

@csrf_exempt
def Rank(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
	courseid = request.POST['form']
	examid = request.POST['form2']
	ranklists = ScoreInfo.objects.filter(ExamID = examid).order_by('-Score')
	print ranklists
	Ranklists =[]
	i = 1
	for ranklist in ranklists:
		Ranklist = {}
		Ranklist['StuID'] = ranklist.StuID
		Ranklist['Score'] = ranklist.Score
		Ranklist['Rank'] = i
		Ranklists.append(Ranklist)
		i = i + 1
		if i == 20:
			break
	context ={
			'CourseName':Course.objects.get(CourseID = courseid).CourseName,
			'ExamName':ExamPaperInfo.objects.get(ExamID = examid).ExamName,
			'ranklists':Ranklists,
			}
	return render(request, 'RankList.html', context)

##出题
@csrf_exempt
def AddExamPaper(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
	if request.POST:
		#print request.POST
		objPost = ExamPaperForm(request.POST)
		ret = objPost.is_valid()
		if ret:
			coursename = objPost.cleaned_data['coursename']
			course = Course.objects.filter(CourseName = coursename)
			if not course:
				courseID = len(Course.objects.all())+1
				Course(CourseID = courseID,CourseName = coursename).save()
			else:
				course = Course.objects.get(CourseName = coursename)
				courseID = course.CourseID
			examname = objPost.cleaned_data['examname']
			examtime = objPost.cleaned_data['examtime']
			problemnum = objPost.cleaned_data['problemnum']
			totalscore = objPost.cleaned_data['totalscore']
			note = objPost.cleaned_data['note']
			now = time.localtime(time.time())
			examid = str(now.tm_year)+'_'+str(now.tm_mon)+'_'+str(now.tm_mday)+'_'+str(now.tm_hour)+'_'+str(now.tm_min)
			ExamPaperInfo(ExamID=examid,ExamName=examname,ExamQuestions='',CourseID=courseID,ExamTime=examtime,ProblemNum=problemnum,TotalScore=totalscore,TeacherID=request.session['UserID'],Note=note).save()
	 		request.session['ExamID'] = examid
	 		request.session['finished'] = 0
	 		request.session['ExamQuestionNum'] = problemnum
			if request.POST['submit'] == u"添加单选题":
				return HttpResponseRedirect('/OnlineExam/AddSingleProblem/')
			elif request.POST['submit'] == u'添加判断题':
				return HttpResponseRedirect('/OnlineExam/AddJudgementProblem/')
	 	else:
	 		pass
	 	return render(request,'AddExamPaper.html',{'obj1':objPost})
	else:
	 	objGet = ExamPaperForm()
	 	return render(request,'AddExamPaper.html',{'obj1':objGet})

@csrf_exempt
def AddSingleProblem(request):
	if not request.session.has_key('ExamID'):
		return HttpResponseRedirect("/OnlineExam/AddExamPaper/")
	#显示已出好的题目
	Questions = []
	examid = request.session['ExamID']
	ex = ExamPaperInfo.objects.get(ExamID = examid)
	examquestions = ex.ExamQuestions
	if examquestions != '':
		examnum = int(ex.ProblemNum) - request.session['ExamQuestionNum']
		i = 0
		for i in range(0,examnum):
			Question ={}
			q = examquestions.split('_',examnum)[i]
			if q[0] =='s':
				question = SingleSelectProblem.objects.get(QuestionID = q[1:])
				Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
				Question['QuestionID'] = 's'+ '_'+ str(question.QuestionID)+'_'+examid
				Question['OptionA'] = question.OptionA
		 		Question['OptionB'] = question.OptionB
		 		Question['OptionC'] = question.OptionC
		 		Question['OptionD'] = question.OptionD
		 		Question['type1'] = 1
		 		Question['type2'] = 0
		 		Question['Weight'] = question.Weight
		 		Question['Answer'] = question.SingleAnswer
		 		Question['Analysis'] = question.Analysis
		 		Question['Note'] = question.Note
		 		Questions.append(Question)
			elif q[0] =='j':
				question = JudgementProblem.objects.get(QuestionID = q[1:])
				Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
				Question['QuestionID'] = 'j'+ '_'+ str(question.QuestionID)+'_'+examid
				Question['type1'] = 0
		 		Question['type2'] = 1
		 		Question['Weight'] = question.Weight
		 		Question['Answer'] = question.JudgementAnswer
		 		Question['Analysis'] = question.Analysis
		 		Question['Note'] = question.Note
		 		Questions.append(Question)
	#提交新表单
	if request.POST:
		objPost = SingleProblemForm(request.POST)
		ret = objPost.is_valid()
		if ret:
			singletitle = objPost.cleaned_data['singletitle']
			optionA = objPost.cleaned_data['optionA']
			optionB = objPost.cleaned_data['optionB']
			optionC = objPost.cleaned_data['optionC']
			optionD = objPost.cleaned_data['optionD']
			singleanswer = objPost.cleaned_data['singleanswer']
			analysis = objPost.cleaned_data['analysis']
			weight = objPost.cleaned_data['weight']
			note = objPost.cleaned_data['note']
			SingleSelectProblem(QuestionID = len(SingleSelectProblem.objects.all())+1,CourseID = ExamPaperInfo.objects.get(ExamID = request.session['ExamID']).CourseID,QuestionTitle = singletitle,OptionA = optionA,OptionB = optionB,OptionC = optionC,OptionD = optionD,SingleAnswer = singleanswer,Analysis = analysis,Weight = weight,Note = note).save()
			Exam = ExamPaperInfo.objects.get(ExamID = request.session['ExamID'])
			Exam.ExamQuestions = Exam.ExamQuestions + 's' + str(len(SingleSelectProblem.objects.all()))
			if request.session['ExamQuestionNum']!=1:
				Exam.ExamQuestions = Exam.ExamQuestions + '_'
			Exam.save();
			request.session['ExamQuestionNum'] -= 1
			if request.session['ExamQuestionNum'] == 1:
				request.session['finished'] = 1
			if request.session['ExamQuestionNum'] == 0:
				return HttpResponseRedirect('/OnlineExam/ShowExamPaper/')
			if request.POST['submit'] == u'添加单选题':
				return HttpResponseRedirect('/OnlineExam/AddSingleProblem/')
			elif request.POST['submit'] == u'添加判断题':
				return HttpResponseRedirect('/OnlineExam/AddJudgementProblem/')
		else:
			finished = request.session['finished']
			context ={
				'obj1':objPost,
		 		'questions':Questions,
		 		'finished':finished,
		 	}
			return render(request,'AddSingleProblem.html',context)
	else:
		objGet = SingleProblemForm()
		finished = request.session['finished']
		context ={
				'obj1':objGet,
		 		'questions':Questions,
		 		'finished':finished,
		 }
		return render(request,'AddSingleProblem.html',context)

@csrf_exempt
def AddJudgementProblem(request):
	if not request.session.has_key('ExamID'):
		return HttpResponseRedirect("/OnlineExam/AddExamPaper/")
	#显示已出好的题目
	Questions = []
	examid = request.session['ExamID']
	ex = ExamPaperInfo.objects.get(ExamID = examid)
	examquestions = ex.ExamQuestions
	if examquestions != '':
		examnum = int(ex.ProblemNum) - request.session['ExamQuestionNum']
		i = 0
		for i in range(0,examnum):
			Question ={}
			q = examquestions.split('_',examnum)[i]
			if q[0] =='s':
				question = SingleSelectProblem.objects.get(QuestionID = q[1:])
				Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
				Question['QuestionID'] = 's'+ '_'+ str(question.QuestionID)+'_'+examid
				Question['OptionA'] = question.OptionA
		 		Question['OptionB'] = question.OptionB
		 		Question['OptionC'] = question.OptionC
		 		Question['OptionD'] = question.OptionD
		 		Question['type1'] = 1
		 		Question['type2'] = 0
		 		Question['Weight'] = question.Weight
		 		Question['Answer'] = question.SingleAnswer
		 		Question['Analysis'] = question.Analysis
		 		Question['Note'] = question.Note
		 		Questions.append(Question)
			elif q[0] =='j':
				question = JudgementProblem.objects.get(QuestionID = q[1:])
				Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
				Question['QuestionID'] = 'j'+ '_'+ str(question.QuestionID)+'_'+examid
				Question['type1'] = 0
		 		Question['type2'] = 1
		 		Question['Weight'] = question.Weight
		 		Question['Answer'] = question.JudgementAnswer
		 		Question['Analysis'] = question.Analysis
		 		Question['Note'] = question.Note
		 		Questions.append(Question)
	if request.POST:
		objPost = JudgementProblemForm(request.POST)
		ret = objPost.is_valid()
		if ret:
			judgementtitle = objPost.cleaned_data['judgementtitle']
			judgementanswer = objPost.cleaned_data['judgementanswer']
			analysis = objPost.cleaned_data['analysis']
			weight = objPost.cleaned_data['weight']
			note = objPost.cleaned_data['note']
			JudgementProblem(QuestionID = len(JudgementProblem.objects.all())+1,CourseID = ExamPaperInfo.objects.get(ExamID = request.session['ExamID']).CourseID,QuestionTitle = judgementtitle,JudgementAnswer = judgementanswer,Analysis = analysis,Weight = weight,Note = note).save()
			Exam = ExamPaperInfo.objects.get(ExamID = request.session['ExamID'])
			Exam.ExamQuestions = Exam.ExamQuestions + 'j' + str(len(JudgementProblem.objects.all()))
			if request.session['ExamQuestionNum']!=1:
				Exam.ExamQuestions = Exam.ExamQuestions + '_'
			Exam.save();
			request.session['ExamQuestionNum'] -= 1
			if request.session['ExamQuestionNum'] == 1:
				request.session['finished'] = 1
			if request.session['ExamQuestionNum'] == 0:
				return HttpResponseRedirect('/OnlineExam/ShowExamPaper/')
			if request.POST['submit'] == u'添加单选题':
				return HttpResponseRedirect('/OnlineExam/AddSingleProblem/')
			elif request.POST['submit'] == u'添加判断题':
				return HttpResponseRedirect('/OnlineExam/AddJudgementProblem/')
		else:
			finished = request.session['finished']
			context ={
				'obj1':objPost,
		 		'questions':Questions,
		 		'finished':finished,
		 	}
			return render(request,'AddJudgementProblem.html',context)
	else:
		objGet = JudgementProblemForm()
		finished = request.session['finished']
		context ={
			'obj1':objGet,
		 	'questions':Questions,
		 	'finished':finished,
		 }
		return render(request,'AddJudgementProblem.html',context)

def ShowExamPaper(request):
	if not request.session.has_key('ExamID'):
		return HttpResponseRedirect("/OnlineExam/AddExamPaper/")
	#显示已出好的题目
	Questions = []
	examid = request.session['ExamID']
	ex = ExamPaperInfo.objects.get(ExamID = examid)
	examquestions = ex.ExamQuestions
	examnum = int(ex.ProblemNum)
	i = 0
	for i in range(0,examnum):
		Question ={}
		q = examquestions.split('_',examnum-1)[i]
		if q[0] =='s':
			question = SingleSelectProblem.objects.get(QuestionID = q[1:])
			Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
			Question['QuestionID'] = 's'+ '_'+ str(question.QuestionID)+'_'+examid
			Question['OptionA'] = question.OptionA
	 		Question['OptionB'] = question.OptionB
	 		Question['OptionC'] = question.OptionC
	 		Question['OptionD'] = question.OptionD
	 		Question['type1'] = 1
	 		Question['type2'] = 0
	 		Question['Weight'] = question.Weight
	 		Question['Answer'] = question.SingleAnswer
	 		Question['Analysis'] = question.Analysis
	 		Question['Note'] = question.Note
	 		Questions.append(Question)
		elif q[0] =='j':
			question = JudgementProblem.objects.get(QuestionID = q[1:])
			Question['QuestionTitle'] = str(i+1) +'. ' + question.QuestionTitle
			Question['QuestionID'] = 'j'+ '_'+ str(question.QuestionID)+'_'+examid
			Question['type1'] = 0
	 		Question['type2'] = 1
	 		Question['Weight'] = question.Weight
	 		Question['Answer'] = question.JudgementAnswer
	 		Question['Analysis'] = question.Analysis
	 		Question['Note'] = question.Note
	 		Questions.append(Question)
	context ={
			'CourseName':Course.objects.get(CourseID = ExamPaperInfo.objects.get(ExamID = request.session['ExamID']).CourseID),
			'ExamName':ExamPaperInfo.objects.get(ExamID = request.session['ExamID']).ExamName,
			'questions':Questions,
	}
	return  render_to_response('ShowExamPaper.html',context)

@csrf_exempt
def ModifyProblem(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps('notLogin'))
	if request.POST:
		ques = {}
		problemID = request.POST.get('ProblemID')
		if problemID[0] == 's':
			questionType = 'SingleProblem'
			questionID = int(problemID.split('_')[1])
			try:
				q = SingleSelectProblem.objects.get(QuestionID = questionID)
			except Exception as e:
				return HttpResponse(json.dumps(e))
			ques['QuestionID'] = q.QuestionID
			ques['QuestionTitle'] = q.QuestionTitle
			ques['SingleAnswer'] = q.SingleAnswer
			ques['OptionA'] = q.OptionA
			ques['OptionD'] = q.OptionD
			ques['OptionC'] = q.OptionC
			ques['OptionB'] = q.OptionB
			ques['Analysis'] = q.Analysis
			ques['Weight'] = q.Weight
			ques['Note'] = q.Note
		else:
			questionType = 'JudgementProblem'
			questionID = int(problemID.split('_')[1])
			try:
				q = JudgementProblem.objects.get(QuestionID = questionID)
			except Exception as e:
				error = {'type': str(e)}
				return HttpResponse(json.dumps(error))
			ques['QuestionID'] = q.QuestionID
			ques['QuestionTitle'] = q.QuestionTitle
			ques['JudgementAnswer'] = q.JudgementAnswer
			ques['Analysis'] = q.Analysis
			ques['Weight'] = q.Weight
			ques['Note'] = q.Note
		info = {
			'type': questionType,
			'question': ques,
		}
		return HttpResponse(json.dumps(info))
	return HttpResponse('Whoops!')

@csrf_exempt
def ModifySingleProblem(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps({'type': 'notLogin'}))
	if request.POST:
		try:
			q = SingleSelectProblem.objects.get(QuestionID = request.POST.get('QuestionID'))
		except Exception as e:
			error = {'type': str(e)}
			return HttpResponse(json.dumps(error))
		q.QuestionTitle = request.POST.get('QuestionTitle')
		q.OptionA = request.POST.get('OptionA')
		q.OptionB = request.POST.get('OptionB')
		q.OptionC = request.POST.get('OptionC')
		q.OptionD = request.POST.get('OptionD')
		q.SingleAnswer = request.POST.get('SingleAnswer')
		q.Analysis = request.POST.get('Analysis')
		print q.Analysis
		q.Weight = request.POST.get('Weight')
		q.Note = request.POST.get('Note')
		q.save()
		ques = {}
		examid = request.session['ExamID']
		ques['QuestionID'] = 's'+ '_'+ str(q.QuestionID)+'_'+examid
		ques['QuestionTitle'] = q.QuestionTitle
		ques['SingleAnswer'] = q.SingleAnswer
		ques['OptionA'] = q.OptionA
		ques['OptionD'] = q.OptionD
		ques['OptionC'] = q.OptionC
		ques['OptionB'] = q.OptionB
		ques['Analysis'] = q.Analysis
		ques['Weight'] = q.Weight
		ques['Note'] = q.Note
		info = {
			'type': 'done',
			'question': ques,
		}
		return HttpResponse(json.dumps(info))
	return HttpResponse('Whoops!')

@csrf_exempt
def ModifyJudgementProblem(request):
	if not request.session.has_key('UserID'):
		return HttpResponse(json.dumps({'type': 'notLogin'}))
	if request.POST:
		try:
			q = JudgementProblem.objects.get(QuestionID = request.POST.get('QuestionID'))
		except Exception as e:
			return HttpResponse(json.dumps({'type': e}))
		q.QuestionTitle = request.POST.get('QuestionTitle')
		q.JudgementAnswer = request.POST.get('JudgementAnswer')
		q.Analysis = request.POST.get('Analysis')
		q.Weight = request.POST.get('Weight')
		q.Note = request.POST.get('Note')
		q.save()
		ques = {}
		examid = request.session['ExamID']
		ques['QuestionID'] = 'j'+ '_'+ str(q.QuestionID)+'_'+examid
		ques['QuestionTitle'] = q.QuestionTitle
		ques['JudgementAnswer'] = q.JudgementAnswer
		ques['Analysis'] = q.Analysis
		ques['Weight'] = q.Weight
		ques['Note'] = q.Note
		info = {
			'type': 'done',
			'question': ques,
		}
		return HttpResponse(json.dumps(info))
	return HttpResponse('Whoops!')
